import user from '@/services/user';
import cookie from 'js-cookie';
import createLoading from '@/components/loading';
import {message} from 'antd';
import {routerRedux} from 'dva/router';
import {history} from 'dva';

console.log(history);

function getNum(){
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve()
        },2000)
    })
}

export default {

    namespace: 'user',  //命名空间

    state: {  //状态
        token:'',
        userInfo:{},        //用户信息
        userViewsData:[]    //用户可访问的菜单列表
    },

    reducers: {  //同步修改状态
        //修改token
        SET_USER_TOKEN(state,{payload}){
            state.token = payload;
            return {...state}
        },
        SET_USERINFO(state,{payload:{userInfo,userViewsData}}){
            return {
                ...state,
                userInfo,
                userViewsData
            }
        }
    },
    effects:{  //异步的任务
        //generator函数
        *LOGIN({info},{call,put}){ //call 执行异步函数 第一个参数：异步函数的函数名 第二个参数：要传递参数  put派发action
            //用户的信息
            //loading展示
            let cancelLoading = createLoading();
            let res = yield call(user.login,info);
            yield getNum();
            //loading消失
            cancelLoading();
            let token = res.token;
            cookie.set('userToken',token,{expires:1});
            yield put({
                type:'SET_USER_TOKEN',
                payload:token
            })
        },
        *GET_USERINFO(action,{call,put}){
            try{
                //获取个人信息
                let {data:userInfo} = yield call(user.getUserInfo);  //user_id
                //获取个人视图权限
                let {data:userViewsData} = yield call(user.getUserViews,userInfo.user_id);
                localStorage.setItem('userViewsData',JSON.stringify(userViewsData))
                yield put({
                    type:'SET_USERINFO',
                    payload:{
                        userInfo,
                        userViewsData
                    }
                })
            }catch(e){
                message.error('token失效或过期');
                //1.把本地的cookie清除    2.定位到登录界面

                cookie.remove('userToken');
                console.log("====");
                
                yield put(routerRedux.push('/login') ); 
            }
        }
    }
};
